package com.sxm.yiwei.pinche;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.pinche.HostOrdersAdapter;
import com.sxm.yiwei.adapters.pinche.PincheOrderListAdapter;
import com.sxm.yiwei.base.BaseFragment;
import com.sxm.yiwei.beans.pinche.HostOrder;
import com.sxm.yiwei.beans.pinche.HttpHead;
import com.sxm.yiwei.beans.pinche.Order;
import com.sxm.yiwei.constant.Common;
import com.sxm.yiwei.constant.Constant;
import com.sxm.yiwei.utils.DateUtil;
import com.sxm.yiwei.views.CenterDialog;
import com.sxm.yiwei.views.PullToRefreshView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;

/**
 * A simple {@link Fragment} subclass.
 */
public class HostOrdersFragment extends BaseFragment{


    private static HostOrdersFragment mFragment;
    private ListView listView;
    private ArrayList<HostOrder> hostOrders;
    private int vehicle_type;
    private ProgressDialog progressDialog;
    private Order order;
    private int page=1;
    private HostOrdersAdapter adapter;
    private View view;
    private int failure_code;
    private CenterDialog centerDialog;
    private RelativeLayout rl_building;
    private PullToRefreshScrollView refreshView;
    private int http_flag=Constant.DEFAULT;


    @Override
    protected int setContentView() {
        return R.layout.fragment_host_orders;
    }

    @Override
    protected void startLoad() {
        ScrollView scrollView = refreshView.getRefreshableView();
        scrollView.smoothScrollTo(0,0);
        searchHostList(order.getStyle(),order.getStart_place(),order.getEnd_place(),order.getDepart_time(),order.getStart_time(),order.getEnd_time(),vehicle_type,page);
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        order = (Order) bundle.getSerializable("order");
        vehicle_type = bundle.getInt("vehicle_type");//0 “大巴”或者1 “私家车”
        hostOrders =new ArrayList<>();

        if (view == null){
            view = getContentView();
        }
        listView = (ListView)view.findViewById(R.id.listView);
        rl_building = (RelativeLayout)view.findViewById(R.id.rl_building);
        refreshView = (PullToRefreshScrollView)view.findViewById(R.id.refresh_view);
        refreshView.setMode(PullToRefreshBase.Mode.BOTH);
        adapter = new HostOrdersAdapter(getActivity(),hostOrders,0);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HostOrder hostOrder = hostOrders.get(i);
                Intent intent = new Intent(getActivity(), HostOrderDetailActivity.class);
                intent.putExtra("hostOrder", hostOrder);
                getActivity().startActivity(intent);
            }
        });
        adapter.setOnBuyTicketListener(new HostOrdersAdapter.OnBuyClickListener() {
            @Override
            public void onBuyClick(int position) {
                HostOrder hostOrder = hostOrders.get(position);
                Intent intent = new Intent(getActivity(), HostOrderDetailActivity.class);
                intent.putExtra("hostOrder", hostOrder);
                getActivity().startActivity(intent);
            }
        });
        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ScrollView> refreshView) {
                page=1;
                http_flag=Constant.REFRESH;
                refreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        searchHostList(order.getStyle(),order.getStart_place(),order.getEnd_place(),order.getDepart_time(),order.getStart_time(),order.getEnd_time(),vehicle_type,page);
                        refreshView.onRefreshComplete();
                    }
                },2000);
            }

            @Override
            public void onPullUpToRefresh(final PullToRefreshBase<ScrollView> refreshView) {
                page++;
                http_flag=Constant.LOAD_MORE;
                refreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        searchHostList(order.getStyle(),order.getStart_place(),order.getEnd_place(),order.getDepart_time(),order.getStart_time(),order.getEnd_time(),vehicle_type,page);
                        refreshView.onRefreshComplete();
                    }
                },2000);
            }
        });
    }
    /*
    * 获取乘客发布列表
    * */
    private void searchHostList(int type, String start_pos, String end_pos, String leave_date, String leave_time, String end_time, final int vehicle_type, final int page){
        progressDialog = ProgressDialog.show(getActivity(),"加载","正在加载中...");

        JSONObject object = new JSONObject();
        object.put("pinServiceKinds",""+type);
        object.put("pinStartPoint", start_pos);
        object.put("pinEndPoint",end_pos);
        if (TextUtils.isEmpty(leave_date)){

        }else {
            if (!TextUtils.isEmpty(leave_time)&&!TextUtils.isEmpty(end_time)){
                object.put("leaveOffTime",leave_date);
                object.put("leftLeaveOffTime",leave_time);
                object.put("rightLeaveOffTime",end_time);
            }else {
                object.put("leaveOffTime",leave_date);
            }
        }

        object.put("vehicleType",vehicle_type+"");
        object.put("pageNo",page+"");
        object.put("pageSize","10");
        Log.d("车主发布服务列表","pinServiceKinds="+type+" pinStartPoint="+start_pos+" pinEndPoint="+end_pos+" leaveOffTime="+leave_date+" leftLeaveOffTime="+leave_time+" rightLeaveOffTime="+end_time+"vehicleType="+vehicle_type+" pageNo"+page);
        final RequestParams params=  new RequestParams(Common.HOST+Common.SEARCH_HOST_SURVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",getHeadInfo().getToken());
        params.addHeader("appId",getHeadInfo().getAppId());
        params.addHeader("userId",getHeadInfo().getUserId());
        Log.d("getHead",getHeadInfo().getToken()+"getHeadInfo  "+getHeadInfo().getAppId()+"getUserId  "+getHeadInfo().getUserId());
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                Log.d("tag"+vehicle_type, "onSuccess: 车主发布服务列表--"+result);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                if (obj.getIntValue("status")==1){
                    Toast.makeText(getActivity(),"请求成功",Toast.LENGTH_SHORT).show();
                    JSONArray data = obj.getJSONArray("data");
                    if (http_flag==Constant.REFRESH||http_flag==Constant.DEFAULT){
                        hostOrders.clear();
                    }else {

                    }
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject jsonObject = data.getJSONObject(i);
                        HostOrder hostOrder = new HostOrder();
                        hostOrder.setStart_time(DateUtil.times(jsonObject.getLongValue("pinCreateTime")));
                        hostOrder.setDepart_time(DateUtil.times(jsonObject.getLongValue("leaveOffTime")));
                        hostOrder.setIcon(jsonObject.getString("ownerAvatar"));
                        hostOrder.setSeats(jsonObject.getIntValue("ownerHasSeats"));
                        hostOrder.setOwner_id(jsonObject.getString("ownerId"));
                        hostOrder.setPhone(jsonObject.getString("ownerMobile"));
                        hostOrder.setEnd_place(jsonObject.getString("pinEndPoint"));
                        if (jsonObject.containsKey("pinLeaveWords")){
                            hostOrder.setWords(jsonObject.getString("pinLeaveWords"));
                        }else {
                            hostOrder.setWords("");
                        }
                        hostOrder.setBreak_money(jsonObject.getDouble("pinLoseAccount"));
                        hostOrder.setPrice(jsonObject.getDouble("pinServiceAccount"));
                        hostOrder.setStyle(jsonObject.getIntValue("pinServiceKinds"));
                        hostOrder.setStart_place(jsonObject.getString("pinStartPoint"));
                        hostOrder.setDistance(jsonObject.getDouble("pinTotalDistance"));
                        hostOrder.setService_id(jsonObject.getString("serviceId"));
                        hostOrder.setVehicle_type(jsonObject.getIntValue("vehicleType"));
                        hostOrder.setNickname(jsonObject.getString("ownerNickName"));
                        hostOrder.setService_code(jsonObject.getString("pinServiceCode"));
                        JSONArray imgs = jsonObject.getJSONArray("vehicleAvatarList");
                        ArrayList<String> imgList = new ArrayList<>();
                        for (int j = 0; j < imgs.size(); j++) {
                            String string = imgs.getString(j);
                            imgList.add(string);
                        }
                        hostOrder.setImgList(imgList);
                        hostOrder.setTotal_price(hostOrder.getPrice()*hostOrder.getSeats());
                        hostOrders.add(hostOrder);
                    }
                    adapter.notifyDataSetChanged();
                    if (hostOrders.size()==0){
                        rl_building.setVisibility(View.VISIBLE);
                        refreshView.setVisibility(View.GONE);
                    }else {
                        rl_building.setVisibility(View.GONE);
                        refreshView.setVisibility(View.VISIBLE);
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag"+vehicle_type, "onError: 车主发布服务列表--"+ex);
                progressDialog.dismiss();

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }




}
